import { reactive, watch } from 'vue'
import { getAllType } from '../api/common'

const loadFn: ((_this: ReturnList) => void)[] = []
const list = reactive<SELECTLIST>({
  zjlx: null
})

const select = reactive<SelectStore>({
  getData(type: number, key: keyof SELECTLIST) {
    getAllType<SELECTDATA>(type)
      .then(({ data }) => {
        list[key] = data.map((item) => {
          return {
            ...item,
            label: item.codeName,
            value: item.code
          }
        })
      })
      .catch(() => {
        list[key] = []
      })
  },
  setData(fn: (_this: ReturnList) => void) {
    if (Object.values(list).some((item) => item === null)) loadFn.push(fn)
    fn(list as ReturnList)
  },
  loadData() {
    select.getData(1, 'zjlx')

    let w: ReturnType<typeof watch>
    w = watch(
      () => Object.values(list),
      (newVal) => {
        loadFn.map((fn) => fn(list as ReturnList))
        if (newVal.every((item) => item !== null)) {
          loadFn.length = 0
          if (w) w()
        }
      },
      { immediate: true }
    )
  }
})

export default select
